<template>
  <div class="main">
    <h4>发表评论</h4><hr>
    <van-cell-group>
      <van-field v-model="newComment" placeholder="请输入评论" />
    </van-cell-group>
    <van-button type="info" size="large" style="margin: 5px 0;" @click="addComment" :text="text" :disabled="btndisabled"></van-button>
    <van-list
      finished-text="没有更多了"
    >
      <div class="content" v-for="(item, index) in goodsComments" :key="index">
        <div class="title">
          <span>第{{index + 1}}楼 </span>
          <span>用户：{{item.user_name}}</span>
          <span>发布时间：{{item.add_time.substr(0, 10)}}</span>
        </div>
        <div class="body">
          {{item.content}}
        </div>
      </div>
    <van-button type="danger" plain size="large" style="margin: 5px 0;" @click="loadingComment">加载评论</van-button>
    </van-list>
  </div>
</template>

<script>
export default {
  data () {
    return {
      page: 1,
      goodsComments: [],
      newComment: '',
      text: '发表评论',
      // 控制按钮是否禁用
      btndisabled: false
    }
  },
  created () {
    this.getGoodsComments()
  },
  methods: {
    // 获取评论
    async getGoodsComments () {
      const { data: res } = await this.$axios.get(`/api/getcomments/${this.$route.params.id}?pageindex=${this.page}`)
      if (res.status !== 0) return this.$notify('获取评论失败')
      this.goodsComments = res.message
    },
    // onLoad () {}
    // 点击加载按钮时
    async loadingComment () {
      this.page++
      const { data: res } = await this.$axios.get(`/api/getcomments/${this.$route.params.id}?pageindex=${this.page}`)
      if (res.status !== 0) return this.$notify('获取评论失败')
      if (res.message.length === 0) {
        this.text = '已加载全部'
        this.btndisabled = true
      }
      this.goodsComments.push(...res.message)
    },
    // 添加评论
    async addComment () {
      if (this.newComment.trim() === '') return this.$notify('请填写评论')
      const { data: res } = await this.$axios.post(`/api/postcomment/${this.$route.params.id}`, { content: this.newComment })
      if (res.status !== 0) return this.$notify('评论失败')
      this.$notify({ type: 'success', message: '评论成功' })
      this.getGoodsComments()
      this.newComment = ''
    }
  }
}
</script>

<style lang="less" scoped>
.main{
  padding: 5px;
}
.van-cell-group{
  border: 1px solid #ccc;
}
.van-field {
  height: 100px;
}
.title {
  background-color: #ccc;
  height: 30px;
  line-height: 30px;
}
.title span{
  font-size: 14px;
  margin-left: 12px;
}
.body{
  line-height: 35px;
  text-indent: 2em;
  font-size: 12px;
}
</style>
